<template>
  <a-table
      class="max-height"
      position="top"
      row-key="id"
      v-if="hasData && data.length > 0"
      :columns="cols"
      :data-source="data"
  >
    <template #boolean="{ text: val }">
      <a-tag :color="val ? '' : 'volcano'">{{ val ? '是' : '否' }}</a-tag>
    </template>
    <template #array="{ text: array }">
      <a-radio-group size="small">
        <a-radio-button v-for="val in array.length" :key="val">{{ array[val - 1] }}</a-radio-button>
      </a-radio-group>
    </template>
    <template #expandedRowRender="{ record }">
      <vue-json-pretty v-if="record" :data="record"/>
    </template>
  </a-table>
  <a-empty v-else/>
</template>

<script>
import VueJsonPretty from 'vue-json-pretty';
export default {
  name: 'UniversalProtoTable.vue',
  props: {
    // 表格数据源
    data: {
      type: Array,
      default: () => {
        return [];
      }
    },
    // 不显示的列，默认全部显示
    ignoreCols: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  setup() {
    return {

    }
  },
  components: {
    VueJsonPretty
  },
  methods: {
    genColRender(col) {
      if (col === undefined || col === null) {
        return undefined;
      }
      if (Array.isArray(col)) {
        return {customRender: 'array'};
      }
      let slot = {
        customRender: undefined
      };
      let dataType = typeof col;
      switch (dataType) {
        // case "bigint":
        //   slot.customRender = 'numberVal';
        //   break;
        // case "number":
        //   slot.customRender = 'numberVal';
        //   break
        case 'boolean':
          slot = {customRender: 'boolean'};
          break;
        case 'object':
          slot = undefined;
          break;
        default:
      }
      return slot;
    }
  },
  computed: {
    cols() {
      let dataArr = this.data;
      if (!dataArr || dataArr.length < 1) {
        return [];
      }
      let data = dataArr[0];
      const colArr = [];
      for (let key in data) {
        if (this.ignoreKeyMap[key]) {
          continue;
        }
        let col = {
          title: key,
          dataIndex: key,
          key: key,
          align: 'center',
          slots: this.genColRender(data[key])
        };
        colArr.push(col);
      }

      return colArr;
    },
    hasData() {
      let data = this.data;
      return data && Array.isArray(data)
    },
    ignoreKeyMap() {
      let ignoreCols = this.ignoreCols;
      const map = {};
      for (let key in ignoreCols) {
        let prop = ignoreCols[key];
        map[prop] = true;
      }
      return map;
    }
  }
}
</script>

<style scoped>

</style>
